/**
 * Created by htzhanglong on 2015/8/2.
 */
// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic','ngCordova','starter.controllers','ionic-native-transitions','starter.config','starter.services','starter.directive','ngResource'])

/*
*     .run(function($ionicPlatform) {
 $ionicPlatform.ready(function() {
 // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
 // for form inputs)
 if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
 cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
 }
 if (window.StatusBar) {
 // org.apache.cordova.statusbar required
 StatusBar.styleLightContent();
 }
 });
 })
* */
  .run(function($rootScope){
    $rootScope.back = function(){
      $ionicHistory.goBack();
      console.log("back");
    };
  })

    .config(function($stateProvider, $urlRouterProvider,$ionicConfigProvider,$httpProvider,$ionicNativeTransitionsProvider) {


        $ionicConfigProvider.platform.ios.tabs.style('standard');
        $ionicConfigProvider.platform.ios.tabs.position('bottom');
        $ionicConfigProvider.platform.android.tabs.style('standard');
        $ionicConfigProvider.platform.android.tabs.position('standard');

        $ionicConfigProvider.platform.ios.navBar.alignTitle('center');
        $ionicConfigProvider.platform.android.navBar.alignTitle('center');

        $ionicConfigProvider.platform.ios.backButton.previousTitleText('').icon('ion-ios-arrow-thin-left');
        $ionicConfigProvider.platform.android.backButton.previousTitleText('').icon('ion-chevron-left');

        $ionicConfigProvider.platform.ios.views.transition('ios');
        $ionicConfigProvider.platform.android.views.transition('android');




        $ionicNativeTransitionsProvider.setDefaultOptions({
          duration: 200, // in milliseconds (ms), default 400,
          slowdownfactor: 4, // overlap views (higher number is more) or no overlap (1), default 4
          iosdelay: -1, // ms to wait for the iOS webview to update before animation kicks in, default -1
          androiddelay: -1, // same as above but for Android, default -1
          winphonedelay: -1, // same as above but for Windows Phone, default -1,
          fixedPixelsTop: 0, // the number of pixels of your fixed header, default 0 (iOS and Android)
          fixedPixelsBottom: 0, // the number of pixels of your fixed footer (f.i. a tab bar), default 0 (iOS and Android)
          triggerTransitionEvent: '$ionicView.afterEnter', // internal ionic-native-transitions option
          backInOppositeDirection: false // Takes over default back transition and state back transition to use the opposite direction transition to go back
        });

        $ionicNativeTransitionsProvider.setDefaultTransition({
          type: 'slide',
          direction: 'left'
        });

        $ionicNativeTransitionsProvider.setDefaultBackTransition({
          type: 'slide',
          direction: 'right'
        });





      // Ionic uses AngularUI Router which uses the concept of states
        // Learn more here: https://github.com/angular-ui/ui-router
        // Set up the various states which the app can be in.
        // Each state's controller can be found in controllers.js
        $stateProvider
            // setup an abstract state for the tabs directive
            .state('tab', {
                url: "/tab",
                abstract: true,
                nativeTransitions: null,
                templateUrl: "templates/tabs.html",
                controller: 'tabCtrl'
            })

            // Each tab has its own nav history stack:

            .state('tab.todo', {
                url: '/todo',
                // nativeTransitions: {
                //   "type": "slide",
                //   "direction": "up"
                // },
                cache:false,
                views: {
                      'tab-todo': {
                          templateUrl: 'templates/todo/todo.html',
                          controller: 'todoCtrl'
                      }
                  }
            })

            .state('tab.task', {
                url: '/task',
                cache:false,
                views: {
                    'tab-task': {
                        templateUrl: 'templates/task/task.html',
                        controller: 'taskCtrl'
                    }
                }
            })

            .state('tab.user', {
                url: '/user',
                views: {
                    'tab-user': {
                        templateUrl: 'templates/user/user.html',
                        controller: 'userCtrl'
                    }
                }
            })
            .state('todo_detail', {
                url: "/todo_detail/:aid",
                cache:false,
                templateUrl: "templates/public/detail.html",
                controller: 'detailCtrl'

             })

            .state('follow_detail', {
                url: "/follow_detail/:aid&:orderId",
                cache:false,
                templateUrl: "templates/public/follow_detail.html",
                controller: 'followDetailCtrl'

            })
            .state('signin', {
                url: "/sign-in",
                templateUrl: "templates/user/login.html",
                controller: 'loginCtrl'
            })
            .state('repair_record', {
                url: "/repair_record",
                templateUrl: "templates/public/repair_record.html",
                controller: 'repairRecordCtrl'
            })
            .state('myInfo', {
                url: "/myInfo",
                templateUrl: "templates/user/myInfo.html",
                controller: 'userCtrl'
            })
            .state('unit_member', {
                url: "/unit_member/:uid",
                templateUrl: "templates/user/unit_member.html",
                controller: 'userCtrl'
            })
            .state('node_report', {
                url: "/node_report/:aid",
                templateUrl: "templates/public/node_report.html",
                controller: 'nodeReportCtrl'
            })
            .state('myUnit', {
              url: "/myUnit",
              templateUrl: "templates/user/myUnit.html",
              controller: 'userCtrl'
            })
            .state('jobType', {
              url: "/jobType",
              templateUrl: "templates/user/jobType.html",
              controller: 'userCtrl'
            })
            .state('mySkilCertificate', {
              url: "/mySkilCertificate",
              templateUrl: "templates/user/skillCertificate.html",
              controller: 'userCtrl'
            })
            .state('knowledge', {
              url: '/knowledge',
              // templateUrl: "templates/user/skillCertificate.html",
              controller: 'knowledgeCtrl'
            })
            .state('modifyPassword', {
              url: '/modifyPassword',
              templateUrl: "templates/user/modifyPassword.html",
              controller: 'userCtrl'
            })
            .state('chooseProduct', {
                url: '/chooseProduct',
                templateUrl: "templates/task/chooseProducts.html",
                controller: 'chooseProductCtrl'
            })
            .state('placeOrder', {
                url: '/placeOrder',
                param:{"productIds":null},
                templateUrl: "templates/task/placeOrder.html",
                controller: 'placeOrderCtrl'
            })
        // if none of the above states are matched, use this as the fallback
        $urlRouterProvider.otherwise('/sign-in');




        //$httpprovider的配置
        // $httpProvider.interceptors.push('authInterceptor');
        $httpProvider.interceptors.push(function($rootScope) {
            return {
                request: function(config) {
                    $rootScope.$broadcast('loading:show');
                    console.log("请求的config"+config);
                    return config
                },
                response: function(response) {
                    $rootScope.$broadcast('loading:hide');
                    console.log("响应的的response");
                    if(response.status==0){
                      Toast.show("网络错误！");
                    }
                    return response
                }
            }
        })


        // Use x-www-form-urlencoded Content-Type
        // $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
        $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';


        // Override $http service's default transformRequest
        $httpProvider.defaults.transformRequest = [function(data)
        {
            /**
                                * The workhorse; converts an object to x-www-form-urlencoded serialization.
                                * @param {Object} obj
                                * @return {String}
                                */
            var param = function(obj)
            {
                var query = '';
                var name, value, fullSubName, subName, subValue, innerObj, i;
                console.log(obj);


                for(name in obj)
                {
                    value = obj[name];
                    console.log(value);


                    if(value instanceof Array)
                    {
                        console.log("Array");
                        for(i=0; i<value.length; ++i)
                        {
                            subValue = value[i];
                            fullSubName = name + '[' + i + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    }
                    else if(value instanceof Object)
                    {
                        console.log("object");
                        for(subName in value)
                        {
                            subValue = value[subName];
                            if(subValue != null){
                                // fullSubName = name + '[' + subName + ']';
                                //user.userName = hmm & user.userPassword = 111
                                fullSubName = name + '.' + subName;
                                // fullSubName =  subName;
                                innerObj = {};
                                innerObj[fullSubName] = subValue;
                                query += param(innerObj) + '&';
                            }
                        }
                    }
                    else if(value !== undefined ) //&& value !== null
                    {
                        console.log("undefined");
                        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
                    }
                }


                return query.length ? query.substr(0, query.length - 1) : query;
            };


            return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
        }]


        $httpProvider.defaults.useXDomain = true;
        // delete $httpProvider.defaults.headers.common['X-Requested-With'];

    })



    .run(function($rootScope, $ionicLoading) {
        $rootScope.$on('loading:show', function() {
            $ionicLoading.show({template: '请求中...'})
        });

        $rootScope.$on('loading:hide', function() {
            $ionicLoading.hide()
        });
    });

